package com.example;

import com.aspose.words.SaveFormat;
import com.example.config.Constants;
import com.example.config.MatchLicense;
import com.example.util.MyFileUtil;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.UUID;

public class Word2Html {

    public static String wordBytes2HtmlString(byte[] wordBytes) throws Exception {
        MatchLicense.init();
        // 创建临时word转html后生成的html文件
        String fileName = System.currentTimeMillis() + "-" + getUUID32();
        String tmpHtmlFilePath =
                Constants.DEFAULT_FOLDER_TMP_GENERATE + "/" + fileName + ".html";
        com.aspose.words.Document doc = new com.aspose.words.Document(new ByteArrayInputStream(wordBytes));
        doc.save(tmpHtmlFilePath, SaveFormat.HTML);
        byte[] htmlBytes = MyFileUtil.readBytes(tmpHtmlFilePath);
        // 删除临时word文件
        //MyFileUtil.deleteFileOrFolder(tmpHtmlFilePath);
        //改写,把图片也删除
        File dir = new File(Constants.DEFAULT_FOLDER_TMP_GENERATE);
        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (file.isDirectory()) {
                continue;
            }
            if (file.getName().contains(fileName)){
                MyFileUtil.deleteFileOrFolder(file);
            }
        }
        return new String(htmlBytes);
    }

    private static String getUUID32() {
        return UUID.randomUUID().toString().replace("-", "").toLowerCase();
    }

    public static final String WORD_FILE = Constants.DEFAULT_FOLDER_TMP + "/市场快讯（第三十期）-20210802.docx";

    public static void main(String[] args) throws Exception {
        String html = wordBytes2HtmlString(MyFileUtil.readBytes(WORD_FILE));
        System.out.println(html);
    }
}
